package com.sugar.psych.assessment.module.business.other;

import cn.hutool.json.JSONUtil;
import com.sugar.psych.assessment.module.business.dal.dataobject.psychquestion.PsychQuestionDO;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @author Y.sugar
 * @since 2025/7/5 15:11
 */
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(List.class)
public class OptionListTypeHandler implements TypeHandler<List<PsychQuestionDO.Option>> {

    @Override
    public void setParameter(PreparedStatement ps, int i, List<PsychQuestionDO.Option> parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, JSONUtil.toJsonStr(parameter));
    }

    @Override
    public List<PsychQuestionDO.Option> getResult(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        return getResult(value);
    }

    @Override
    public List<PsychQuestionDO.Option> getResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        return getResult(value);
    }

    @Override
    public List<PsychQuestionDO.Option> getResult(CallableStatement cs, int columnIndex) throws SQLException {
        String value = cs.getString(columnIndex);
        return getResult(value);
    }

    private List<PsychQuestionDO.Option> getResult(String value) {
        if (value == null) {
            return null;
        }
        return JSONUtil.toList(value, PsychQuestionDO.Option.class);
    }
}
